<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="65px">
        <el-form-item label="工厂">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.plantId"
            placeholder="请选择工厂"
            clearable
            @change="selectPlant"
          >
            <el-option
              v-for="item in plantList"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作中心">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.workCenterId"
            placeholder="请选择工作中心"
            clearable
            filterable
            @change="chnageWorkCenter"
          >
            <el-option
              v-for="item in workShopList"
              :key="item.id"
              :label="`${item.workshopCode}-${item.workshopName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作年份">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.planYear"
            placeholder="请选择工作年份"
            clearable
            @change="selectYear"
          >
            <el-option
              v-for="item in yearOptions"
              :key="item"
              :value="item"
              :label="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作周">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.planWeek"
            placeholder="请选择工作周"
            clearable
            @change="selectWeek"
          >
            <el-option
              v-for="item in monthOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="生产批次">
          <el-input
            v-model="searchParam.planBatch"
            placeholder="请输入生产批次"
            clearable
            @keyup.enter="search"
          />
        </el-form-item> -->
        <el-form-item>
          <!-- <el-popconfirm
            title="请确认当前数据是否已被保存，切换后未保存的数据会被清空，是否切换?"
            confirm-button-text="切换"
            cancel-button-text="取消"
            :width="300"
            @confirm="startSearch"
          >
            <template #reference>
              <el-button v-show="tableData && tableData.length" type="primary"
                ><i-ep-search />切换</el-button
              >
            </template>
</el-popconfirm>
<el-button v-show="!tableData || !tableData.length" type="primary" @click="startSearch"><i-ep-search />切换</el-button>
-->
          <el-button type="primary" @click="startSearch"
            ><i-ep-search />切换</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="addPlan"
          ><i-ep-plus />新增行</el-button
        >
        <!-- <el-button
          type="primary"
          :loading="planSubmitbLoading"
          @click="validIsSearched('计划确认')"
          >计划确认</el-button
        > -->
        <el-button @click="weekBatchImport"
          ><template #icon><i-ep-upload /></template>导入周计划</el-button
        >
        <!-- <el-button @click="dailyBatchImport"
          ><template #icon><i-ep-upload /></template>导入日计划</el-button
        > -->
        <el-button class="ml-3" @click="downLoadExcel">
          <template #icon><i-ep-download /></template>导出</el-button
        >

        <div style="float: right">
          <el-button
            type="primary"
            :loading="saveLoading"
            @click="validIsSearched('保存')"
            >保 存</el-button
          >
          <el-button
            type="primary"
            @click="validIsSearched('下达')"
            :loading="issueLoading"
            >下 达</el-button
          >
          <el-button
            type="primary"
            @click="validIsSearched('设备')"
            :loading="changeDeviceLoading"
            >设 备</el-button
          >
          <el-button
            type="primary"
            @click="validIsSearched('暂停')"
            :loading="pauseLoading"
            >暂 停</el-button
          >
          <el-button
            type="primary"
            @click="validIsSearched('取消暂停')"
            :loading="cancelPauseLoading"
            >取消暂停</el-button
          >
          <el-button
            type="primary"
            @click="validIsSearched('变更提交')"
            :loading="changeSubLoading"
            >变更提交</el-button
          >
          <el-button
            type="danger"
            @click="validIsSearched('关闭')"
            :loading="closeLoading"
            >关 闭</el-button
          >
          <el-button
            type="danger"
            @click="validIsSearched('删除')"
            :loading="deleteLoading"
            >删 除</el-button
          >
        </div>
        <!-- 导入周计划 -->
        <ImportExcel ref="weekImportRef" />
        <!-- 导入日计划 -->
        <ImportExcel ref="dailyImportRef" />
      </template>

      <el-form
        ref="formRef"
        :model="tableData"
        :rules="rules"
        label-width="90px"
        style="width: 100%"
        class="require-form planTable"
      >
        <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="tableData"
          highlight-current-row
          :span-method="(param) => objectSpanMethod(param, 12)"
          :show-summary="true"
          max-height="600"
          border
          :header-cell-style="{ backgroundColor: '#fff' }"
          :summary-method="
            (param) => getSummaries(param, maxCapacityLoad, 12, tableLoadRate)
          "
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" fixed />
          <el-table-column
            label="总成//工序-人数-版本号"
            prop="materialId"
            min-width="250"
            show-overflow-tooltip
            align="left"
            fixed
          >
            <template #default="{ $index, row }">
              <!-- 分行校验的关键在于:prop="'grossProfits.' + $index + '.name'" -->
              <el-form-item
                v-if="row.planState == 0"
                :prop="$index + '.routingAllocationId'"
                :rules="rules.routingAllocationId"
                label-width="0px"
              >
                <el-select
                  v-model="row.routingAllocationId"
                  placeholder="请选择"
                  @change="(e) => changeRoutingAllocation(e, $index)"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in routingAllocationIdList"
                    :key="item.id"
                    :value="item.id"
                    :label="`${item.descriptionCode}-${item.versionNo}`"
                    small
                  />
                </el-select>
              </el-form-item>

              <!-- :disabled="
                      selectedRoutingAllocationIds.indexOf(item.id) !== -1 ||
                      selectedRoutingAllocationPlan.indexOf(item.planBatch) !==s
                        -1
                    " -->
              <span v-else>{{
                `${row.descriptionCode}-${row.versionNo}`
              }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="卷料" width="60" align="center">
            <template #default="{ row, $index }">
              <svg-icon
                icon-class="material"
                class="text-[17px] !mr-[0px] cursor-pointer color-[#409eff]"
                @click="selectMaterials(row, $index)"
              />
            </template>
          </el-table-column> -->
          <!-- <el-table-column
            label="总成"
            prop="materialCode"
            width="85"
            show-overflow-tooltip
            header-align="center"
            align="center"
          /> -->
          <el-table-column
            label="班产"
            prop="yield"
            width="85"
            show-overflow-tooltip
            header-align="center"
            align="right"
          >
            <template #default="{ $index, row }">
              <!-- 分行校验的关键在于:prop="'grossProfits.' + $index + '.name'" -->
              <el-form-item
                :prop="$index + '.yield'"
                :rules="rules.yield"
                label-width="0px"
                v-if="row.planState != 5"
              >
                <el-input
                  v-model="row.yield"
                  placeholder="请输入"
                  clearable
                  small
                  @blur="(e) => handleBlurYield(e, $index)"
                />
              </el-form-item>
              <span v-else>{{ row.yield }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            prop="planState"
            min-width="100"
            align="center"
          >
            <template #default="scope">
              <el-tag v-show="scope.row.planState == 0" type="success">{{
                useDictionary("PlanStateList", scope.row.planState ?? "")
              }}</el-tag>
              <el-tag v-show="scope.row.planState != 0">{{
                useDictionary("PlanStateList", scope.row.planState ?? "")
              }}</el-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="是否临时"
            prop="isCasual"
            min-width="100"
            align="center"
          >
            <template #default="scope">
              <el-tag v-show="scope.row.isCasual == 0" type="info">{{
                useDictionary("YesNo", scope.row.isCasual ?? "")
              }}</el-tag>
              <el-tag v-show="scope.row.isCasual != 0" type="success">{{
                useDictionary("YesNo", scope.row.isCasual ?? "")
              }}</el-tag>
            </template>
          </el-table-column> -->
          <el-table-column
            label="是否暂停"
            prop="isPause"
            min-width="100"
            align="center"
          >
            <template #default="scope">
              <el-tag v-show="scope.row.isPause == 0" type="success">{{
                useDictionary("YesNo", scope.row.isPause ?? "")
              }}</el-tag>
              <el-tag v-show="scope.row.isPause != 0" type="warning">{{
                useDictionary("YesNo", scope.row.isPause ?? "")
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="周计划数量"
            prop="planWeekQuantity"
            width="85"
            show-overflow-tooltip
            header-align="center"
            align="right"
          />
          <el-table-column
            label="计划数量"
            prop="planQuantity"
            min-width="140"
            show-overflow-tooltip
            align="right"
          >
            <template #default="{ $index, row }">
              <!-- 分行校验的关键在于:prop="'grossProfits.' + $index + '.name'" -->
              <el-form-item
                v-if="row.planState != 5"
                :prop="$index + '.planQuantity'"
                :rules="rules.planQuantity"
                label-width="0px"
              >
                <el-input
                  v-model="row.planQuantity"
                  v-if="row.planState == 0"
                  placeholder="请输入"
                  clearable
                  small
                  @change="(e) => changePlanQuantity(e, $index)"
                >
                  <template #append
                    ><el-button
                      :loading="row.autoAllocationLoading"
                      link
                      class="m-0 text-[12px] cursor-pointer autoAllocation"
                      style="margin: 0px !important"
                      @click="rulePlanQuantity(row.planQuantity, $index)"
                      >分配</el-button
                    >
                  </template>
                </el-input>
                <el-input
                  v-else
                  v-model="row.planQuantity"
                  placeholder="请输入"
                  clearable
                  small
                  @change="(e) => changePlanQuantity(e, $index)"
                />
              </el-form-item>
              <span v-else>{{ row.planQuantity }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="周计划率"
            prop="planWeekQuantityRate"
            width="85"
            show-overflow-tooltip
            header-align="center"
            align="right"
          />
          <el-table-column
            label="生产批次"
            prop="planBatch"
            min-width="100"
            show-overflow-tooltip
            align="right"
          >
            <template #default="{ $index, row }">
              <!-- 分行校验的关键在于:prop="'grossProfits.' + $index + '.name'" -->
              <el-form-item
                v-if="row.planState == 0"
                :prop="$index + '.planBatch'"
                :rules="rules.planBatch"
                label-width="0px"
              >
                <el-input
                  v-model="row.planBatch"
                  placeholder="请输入"
                  clearable
                  small
                />
              </el-form-item>
              <span v-else>{{ row.planBatch }}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="未排数量"
            prop="unPlanQuantity"
            width="85"
            show-overflow-tooltip
            header-align="center"
            align="right"
          />

          <el-table-column
            label="已完成数量"
            prop="planFinishQuantity"
            width="95"
            show-overflow-tooltip
            header-align="center"
            align="right"
          />
          <el-table-column
            label="换型时长(分钟)"
            prop="transferTime"
            min-width="120"
            show-overflow-tooltip
            align="right"
          >
            <template #default="{ $index, row }">
              <!-- 分行校验的关键在于:prop="'grossProfits.' + $index + '.name'" -->
              <el-form-item
                :prop="$index + '.transferTime'"
                :rules="rules.transferTime"
                label-width="0px"
                v-if="row.planState != 5"
              >
                <el-input
                  v-model="row.transferTime"
                  placeholder="请输入"
                  clearable
                  small
                  @blur="(e) => handleBlur(e, $index)"
                />
              </el-form-item>
              <span v-else>{{ row.transferTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="" width="60" align="center">
            <template #default="{ row, $index }">
              <span class="text-[13px]" v-if="($index + 1) % 2 !== 0"
                >计划</span
              >
              <span class="text-[13px]" v-else>实际</span>
            </template>
          </el-table-column>

          <el-table-column :label="`CW${searchParam.planWeek}`" align="center">
            <template #default="">
              <el-table-column
                v-for="(item, index) in currentWeekDetail"
                :key="index"
                :label="`${item.date} 周${ToChineseDate(item.week)}`"
                :label-class-name="`${item.isFree ? 'bg-free' : ''}`"
              >
                <el-table-column
                  v-for="(monthItem, monthIndex) in classCount"
                  :label="`${convertToChineseNumber(monthItem, 2)}班`"
                  :key="monthIndex"
                  :prop="`planQuantity_${index}_${monthIndex}`"
                  class-name="percent_cell"
                  header-align="center"
                  align="right"
                  :label-class-name="`${item.isFree ? 'bg-free' : ''}`"
                >
                  <template #default="{ row, $index }">
                    <div
                      v-if="($index + 1) % 2 !== 0"
                      @click="
                        open(
                          row,
                          $index,
                          index,
                          monthIndex,
                          row?.newOrders[index]?.newClasses[monthIndex]
                            ?.planQuantity
                        )
                      "
                    >
                      <span
                        :class="
                          row?.newOrders[index]?.newClasses[monthIndex]
                            ?.planState == 5
                            ? 'text-coolGray'
                            : ''
                        "
                      >
                        {{
                          row?.newOrders[index]?.newClasses[monthIndex]
                            ?.planQuantity ?? ""
                        }}
                      </span>
                    </div>
                    <!-- fef0f0 -->
                    <div v-else class="bg-[#fef0f0]">
                      <span
                        :class="
                          row?.newOrders[index]?.newClasses[monthIndex]
                            ?.planState === 5
                            ? 'text-coolGray'
                            : ''
                        "
                      >
                        {{
                          row?.newOrders[index]?.newClasses[monthIndex]
                            ?.planFinishQuantity ?? ""
                        }}
                      </span>
                    </div>
                  </template>
                </el-table-column>
              </el-table-column>
            </template>
          </el-table-column>

          <!-- <el-table-column
            label="操作"
            width="120"
            align="center"
            fixed="right"
          >
            <template #default="{ row, $index }">
              <el-button
                type="danger"
                link
                class="text-[13px]"
                @click="deletePlan($index)"
                >删除</el-button
              >
              <el-button
                type="danger"
                link
                class="text-[13px]"
                @click="deletePlan($index)"
                >关闭</el-button
              >
            </template>
          </el-table-column> -->
        </el-table>
      </el-form>
    </el-card>
    <el-dialog
      :close-on-click-modal="false"
      v-model="dialogVisible"
      title="计划排产数量"
      width="450"
      align-center
      draggable
      class="planDialog"
      @close="clearRuleForm"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rulesPlan"
        label-width="auto"
        label-position="left"
        class="demo-ruleForm"
        status-icon
      >
        <div class="mb-[6px]">
          {{ `未排产数量：${ruleForm.unPlanQuantity}`
          }}{{ `班产数量：${ruleForm.yelid}` }}
          {{ `剩余班产数量：${ruleForm.noYelid}` }}
        </div>
        <el-form-item prop="quantity">
          <el-input
            v-model="ruleForm.quantity"
            placeholder="请输入计划排产数量"
            ref="inputRef"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="clearRuleForm">取消</el-button>
          <el-button type="primary" @click="submitPlanQuantity">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 后加的代码--选择设备弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="equDialogVisible"
      title="计划设备"
      width="450"
      align-center
      draggable
      class="planDialog"
      @close="clearRuleEqu"
      destroy-on-close
    >
      <el-form
        ref="formDataRef"
        :model="formData"
        label-width="auto"
        :rules="rulesFormData"
        label-position="left"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="请选择工序" prop="process">
              <el-select
                style="width: 100%"
                v-model="process"
                placeholder="请选择请选择工序"
                clearable
                @change="changProcess"
              >
                <el-option
                  v-for="item in processList"
                  :label="`${item.processCode}-${item.processName}`"
                  :value="`${item.processId}`"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="请选择设备">
              <el-select
                style="width: 100%"
                multiple
                v-model="equipment"
                placeholder="请选择设备"
                clearable
                @change="changEquipment"
              >
                <el-option
                  v-for="item in equipmentList"
                  :label="`${item.equipmentCode}-${item.equipmentName}`"
                  :value="`${item.equipmentId}`"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="clearRuleEqu">取消</el-button>
          <el-button type="primary" @click="saveEqu"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导入失败错误信息弹窗 -->
    <upload-error-table ref="uploadErrorRef" :errorDataList="errorDataList" />
  </div>
</template>

<script setup lang="ts">
import { useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useUserStore } from "@/store/modules/user";
// import { getPlantsApi, getYearsApi, getWorkShopsApi } from "@/api/plant/index";
import {
  getPlantList,
  getFirstWorkShopList,
  getMesRouteGroupList,
  getWorkCenterDetail,
  getCurrentYield,
  getFreeDetails,
  getMonthList,
  getYearList,
  getMaterialList,
  getDateshiftCount,
  getOtherWorkShopList,
} from "@/utils/commonData";
import {
  getWeeksInYear,
  getWeekNumber,
  week_date,
  getDaysOfCurrentWeek,
} from "@/utils/dateUtils";
import type { TableColumnCtx } from "element-plus";
import { convertToChineseNumber, validateNumber } from "@/utils/commonHooks";
import {
  getOneLineDate,
  WeekDetailType,
  SpanMethodProps,
  SearchType,
  resolveSearchData,
  resolveSaveData,
  ToChineseDate,
  getCurrentWeekDetail,
  objectSpanMethod,
  calculateLoadRate,
  getSummaries,
  mockData,
  getNameInfo,
  deepCopy,
} from "@/views/mes/weeklyProducePlan/index";
// import Big from "big.js";

defineOptions({
  name: "MESWEEKLYPRODUCEPLANASSEM",
  inheritAttrs: false,
});

const planType = ref("5");

const userPlantInfo = computed(() =>
  useUserStore().userPlantInfo ? JSON.parse(useUserStore().userPlantInfo) : {}
);
// 换型时间
async function handleBlur(e, index) {
  formRef.value
    .validateField(index + ".transferTime")
    .then(async (res) => {
      const resultTableData = deepCopy(toRaw(tableData.value));
      // resultTableData[index].autoAllocation = 1;
      // resultTableData[index + 1].autoAllocation = 1;
      const result = resolveSaveData(resultTableData);
      // tableData.value[index].autoAllocationLoading = true;
      // const { data, code } = await request({
      //   url: "/mes/mesworkorder/autoAllocation",
      //   method: "post",
      //   data: result,
      // }).finally(() => {
      //   tableData.value[index].autoAllocationLoading = true;
      // });
      // if (code === 200) {

      tableLoadRate.value = await calculateLoadRate(result);
      console.log(tableLoadRate.value);

      // tableData.value = resolveSearchData(
      //   data,
      //   currentWeekDetail.value,
      //   toRaw(searchParam.value.planYear)
      // );

      // // 计算当前未排数量
      // data?.forEach((item, index) => {
      //   const selfIndex = (index + 1) * 2 - 2;
      //   computedUnPlanQuantity(selfIndex);
      // });

      // 获取当前页面已选的物料号ids
      // getSelectedAllocationIds();
      // }
    })
    .catch(() => {});
}

async function handleBlurYield(e, index) {
  formRef.value
    .validateField(index + ".yield")
    .then(async (res) => {
      const resultTableData = deepCopy(toRaw(tableData.value));
      // resultTableData[index].autoAllocation = 1;
      // resultTableData[index + 1].autoAllocation = 1;
      const result = resolveSaveData(resultTableData);
      // tableData.value[index].autoAllocationLoading = true;
      // const { data, code } = await request({
      //   url: "/mes/mesworkorder/autoAllocation",
      //   method: "post",
      //   data: result,
      // }).finally(() => {
      //   tableData.value[index].autoAllocationLoading = true;
      // });
      // if (code === 200) {

      tableLoadRate.value = await calculateLoadRate(result);
      console.log(tableLoadRate.value);

      // tableData.value = resolveSearchData(
      //   data,
      //   currentWeekDetail.value,
      //   toRaw(searchParam.value.planYear)
      // );

      // // 计算当前未排数量
      // data?.forEach((item, index) => {
      //   const selfIndex = (index + 1) * 2 - 2;
      //   computedUnPlanQuantity(selfIndex);
      // });

      // 获取当前页面已选的物料号ids
      // getSelectedAllocationIds();
      // }
    })
    .catch(() => {});
}

const dialogVisible = ref(false);
const ruleForm: any = reactive({
  quantity: "",
  rowData: null,
  rowIndex: null,
  monthIndex: null,
  cellIndex: null,
  unPlanQuantity: null,
  yelid: "",
  noYelid: "",
});

// 改变工作中心
const chnageWorkCenter = () => {
  isSearched.value = false;
};
const selectWeek = () => {
  isSearched.value = false;
};

// 进入弹窗聚焦
// 进入页面聚焦
const inputRef = ref();
const readonly = ref(true);
const inputAutoFocus = () => {
  nextTick(() => {
    readonly.value = true;
    inputRef.value.focus();
    setTimeout(() => {
      inputRef.value.focus();
      readonly.value = false;
    }, 0);
  });
};

const checkPlanQuantity = (rule: any, value: any, callback: any) => {
  // 可以为空
  if (!value) {
    return callback();
  }

  // 校验是否为数字
  const commonValue = Number(value);
  if (Number.isNaN(commonValue) && value) {
    return callback(`请输入数字`);
  }

  // 校验不能为复数
  if (commonValue < 0) {
    return callback(`请输入正确的数字`);
  }

  // 校验总数是否超过计划数量
  const { rowIndex, monthIndex, cellIndex } = ruleForm;
  const computedTableData = deepCopy(toRaw(tableData.value)); // 操作的tabledata

  // 基础上后改的代码-- 导入之后可以为0 只限制新增时
  if (value == 0 && computedTableData[rowIndex].planState * 1 == 0) {
    return callback();
  }

  let sumPlanCount = 0;
  if (
    computedTableData[rowIndex].planState * 1 != 2 &&
    computedTableData[rowIndex].planState * 1 != 3
  ) {
    computedTableData[rowIndex].newOrders.map((item, itemIndex) => {
      item.newClasses.map((cellItem, newIndex) => {
        if (cellItem.planQuantity) {
          // 当前数据不添加
          if (monthIndex === itemIndex && cellIndex === newIndex) {
          } else {
            sumPlanCount += cellItem.planQuantity * 1;
          }
        }
      });
    });
    if (
      sumPlanCount + value * 1 >
      computedTableData[rowIndex].planQuantity * 1
    ) {
      const maxCount =
        computedTableData[rowIndex].planQuantity * 1 - sumPlanCount * 1;
      console.log(
        maxCount,
        sumPlanCount + value * 1,
        computedTableData[rowIndex].planQuantity * 1
      );
      return callback(
        `不能超过${parseInt(maxCount)},当前行计划之和不能超过总计划数量`
      );
    }
  }

  // 后加的代码-- 校验生产中、已下达的计划数量不能小于实际数量
  if (
    computedTableData[rowIndex].planState * 1 == 2 ||
    computedTableData[rowIndex].planState * 1 == 3
  ) {
    let noPlanQuantity = false;
    if (
      ids.value.indexOf(computedTableData[rowIndex]?.key) !== 1 &&
      computedTableData[rowIndex].id !== ""
    ) {
      if (
        value * 1 <
        computedTableData[rowIndex].newOrders[monthIndex].newClasses[cellIndex]
          .planFinishQuantity
      ) {
        noPlanQuantity = true;
      }
    }

    if (noPlanQuantity) {
      // ElMessage.error("生产中、已下达的计划数量不能小于实际数量");
      return callback(`生产中、已下达的计划数量不能小于实际数量`);
    }
  }
  //
  let elderData: any = deepCopy(toRaw(tableData.value));
  elderData[rowIndex].newOrders[monthIndex].newClasses[cellIndex].planQuantity =
    value;
  elderData[rowIndex + 1].newOrders[monthIndex].newClasses[
    cellIndex
  ].planQuantity = value;

  const result = resolveSaveData(elderData);

  calculateLoadRate(result)
    .then((res: any) => {
      console.log("res", res, res[monthIndex * 3 + cellIndex]);
      const currentLoad = res[monthIndex * 3 + cellIndex] ?? "";
      if (Number(currentLoad) > maxCapacityLoad.value / 100) {
        return callback(
          `负荷率不能超过${(maxCapacityLoad.value / 100).toFixed(
            2
          )}，当前负荷率为${currentLoad}请重新分配`
        );
      } else {
        return callback();
      }
    })
    .catch(() => {
      return callback();
    });
};

const rulesPlan = reactive({
  quantity: [{ validator: checkPlanQuantity, trigger: "blur" }],
});

function clearRuleForm() {
  ruleFormRef.value.clearValidate();
  dialogVisible.value = false;
  ruleForm.rowIndex = null;
  ruleForm.monthIndex = null;
  ruleForm.cellIndex = null;
  ruleForm.rowData = null;
  ruleForm.quantity = "";
  ruleForm.yelid = "";
  ruleForm.noYelid = "";
}

const ruleFormRef = ref();
const submitPlanQuantity = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      let { rowIndex, monthIndex, cellIndex, rowData, quantity } = ruleForm;
      if (!quantity) {
        quantity = 0;
      }
      let elderData: any = deepCopy(toRaw(tableData.value));
      elderData[rowIndex].newOrders[monthIndex].newClasses[
        cellIndex
      ].planQuantity = quantity ?? 0;
      elderData[rowIndex + 1].newOrders[monthIndex].newClasses[
        cellIndex
      ].planQuantity = quantity ?? 0;

      const result = resolveSaveData(elderData);

      tableLoadRate.value = await calculateLoadRate(result);
      // 修改第一行
      tableData.value[rowIndex].newOrders[monthIndex].newClasses[
        cellIndex
      ].planQuantity = quantity;
      // 修改第二行
      tableData.value[rowIndex + 1].newOrders[monthIndex].newClasses[
        cellIndex
      ].planQuantity = quantity;
      computedUnPlanQuantity(rowIndex);

      clearRuleForm();
    } else {
      console.log("error submit!");
    }
  });
};

/** 定义form信息 */
const rules = reactive({
  routingAllocationId: [
    { required: true, message: "请选择", trigger: "change" },
  ],
  planQuantity: [
    { required: true, message: "请输入", trigger: "blur" },
    {
      validator: validateNumber,
      trigger: "blur",
    },
  ],
  planBatch: [
    { required: true, message: "请输入", trigger: "blur" },
    {
      validator: validateNumber,
      trigger: "blur",
    },
  ],
  transferTime: [
    { required: true, message: "请输入", trigger: "blur" },
    {
      validator: validator,
      trigger: "blur",
    },
  ],
  yield: [
    { required: true, message: "请输入", trigger: "blur" },
    {
      validator: validatorYield,
      trigger: "blur",
    },
  ],
});

function validator(rule, value, callback: (a?: any) => {}) {
  if (!value && value !== 0) {
    //先判断空可以过
    callback(new Error("请输入数字"));
  } else {
    if (/^[+]{0,1}(\d+)$/.test(value)) {
      //验证正整数和0的正则
      return true;
    } else {
      callback(new Error("请输入数字"));
    }
  }
}
function validatorYield(rule, value, callback: (a?: any) => {}) {
  console.log(value);

  if (!value) {
    //先判断空可以过
    callback(new Error("请输入数字"));
  } else {
    if (value == 0) {
      callback(new Error("请输入数字"));
    }

    if (/^[+]{0,1}(\d+)$/.test(value)) {
      //验证正整数和0的正则
      return true;
    } else {
      callback(new Error("请输入数字"));
    }
  }
}
const formRef = ref(ElForm);

const currentYear = new Date().getFullYear(); // 当前年份
const currentWeek = getWeekNumber(new Date()); // 当前第几周
const classCount = 3; // 固定三个班次

// 表格日期对象 [{date: '05/06', week: 1}, {date: '05/07', week: 2}...]
const currentWeekDetail: any = ref<WeekDetailType[]>([]);
const freeDayDetail: any = ref([]);

// 初始化搜索参数数据
const searchParamInit = {
  planWeek: currentWeek,
  planYear: currentYear,
  workCenterId: "",
  plantId: userPlantInfo.value?.id || "",
  planBatch: "",
  isCasual: "0",
};

const searchedParams = ref();

const isSearched = ref(false); // 是否已搜索
let tableData: any = ref([]); // 表格数据

function validIsSearched(type) {
  if (!isSearched.value) {
    ElMessage.error("请切换到对应排产后，再操作");
    return;
  } else if (!searchParam.value.plantId) {
    ElMessage.error("请选择工厂");
    return;
  } else if (!searchParam.value.workCenterId) {
    ElMessage.error("请选择工作中心");
    return;
  } else if (!searchParam.value.planYear) {
    ElMessage.error("请选择年份");
    return;
  } else if (!searchParam.value.planWeek) {
    ElMessage.error("请选择工作周");
    return;
  } else {
    if (type === "保存") {
      savePlan(tableData.value, "保存");
    } else if (type === "下达") {
      issueOrders();
    } else if (type === "关闭") {
      closePlan();
    } else if (type === "删除") {
      deletePlan();
    } else if (type === "暂停") {
      pausePlan();
    } else if (type === "取消暂停") {
      cancelPausePlan();
    } else if (type === "变更提交") {
      changeSubmission();
    } else if (type === "设备") {
      changeDevice();
    } else if (type === "计划确认") {
      planSubmit();
    }
  }
}
// 添加表格行
function addPlan() {
  if (!isSearched.value) {
    ElMessage.error("请切换到对应排产后，再添加");
    return;
  } else {
    const oneTable = getOneLineDate(
      currentWeekDetail.value,
      searchParam.value.planYear,
      currentYield.value,
      searchedParams.value
    );
    oneTable[0].groupType = 5;
    oneTable[1].groupType = 5;
    tableData.value = [...toRaw(tableData.value), oneTable[0], oneTable[1]];
    console.log(tableData.value);
  }
}

const ids = ref<string[]>([]);

/** 行复选框选中  */
function handleSelectionChange(selection: any) {
  // 存入唯一值，已保存过的存id, 未保存过的存key
  ids.value = selection.map((item: any) => item.id || item.key);
}

// 批量关闭
const closeLoading = ref(false);
function closePlan() {
  if (!ids.value.length) {
    ElMessage.warning("请选择数据");
    return;
  } else {
    ElMessageBox.confirm(
      "未下达和已暂停数据不能关闭，请确认是否关闭所选数据?",
      "提示",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(async () => {
        let listIds: any = ""; //第几行数据  不能关闭提示
        const resultTableData = deepCopy(toRaw(tableData.value));
        resultTableData.map((item: any, index: number) => {
          if (
            item.planState * 1 === 0 &&
            (ids.value.indexOf(item.id) !== -1 ||
              ids.value.indexOf(item?.key) !== -1)
          ) {
            if (index % 2 === 0) {
              const newLine = (index + 2) / 2;
              listIds += `第${newLine}行、`;
            }
          } else if (
            ids.value.indexOf(item.id) !== -1 &&
            item.isPause * 1 === 1
          ) {
            if (index % 2 === 0) {
              const newLine = (index + 2) / 2;
              listIds += `第${newLine}行、`;
            }
          } else if (
            item.planState * 1 > 0 &&
            ids.value.indexOf(item.id) !== -1 &&
            item.isPause * 1 === 0
          ) {
            item.planState = 5;
          }
        });
        if (listIds.length) {
          // 提示未下达过的计划，不能关闭
          listIds = listIds.slice(0, listIds.length - 1);
          ElMessage.error(`${listIds}不能关闭，请重新选择`);
          return;
        }
        // 走关闭成功状态更新接口保存计划
        savePlan(resultTableData, "关闭");
        // ElMessage.success("批量关闭成功");
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消关闭",
        });
      });
  }
}

// 批量暂停
const pauseLoading = ref(false);
function pausePlan() {
  if (!ids.value.length) {
    ElMessage.warning("请选择数据");
    return;
  } else {
    ElMessageBox.confirm(
      "只有已下达和生产中的计划可以暂停，请确认是否暂停所选数据?",
      "提示",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(async () => {
        let listIds: any = ""; //第几行数据  不能关闭提示
        const resultTableData = deepCopy(toRaw(tableData.value));
        resultTableData.map((item: any, index: number) => {
          if (
            item.planState * 1 !== 2 &&
            item.planState * 1 !== 3 &&
            (ids.value.indexOf(item.id) !== -1 ||
              ids.value.indexOf(item?.key) !== -1)
          ) {
            if (index % 2 === 0) {
              const newLine = (index + 2) / 2;
              listIds += `第${newLine}行、`;
            }
          } else if (
            (item.planState * 1 === 2 || item.planState * 1 === 3) &&
            (ids.value.indexOf(item.id) !== -1 ||
              ids.value.indexOf(item?.key) !== -1)
          ) {
            item.isPause = 1;
          }
        });
        if (listIds.length) {
          // 提示未下达过的计划，不能关闭
          listIds = listIds.slice(0, listIds.length - 1);
          ElMessage.error(`${listIds}不能暂停，请重新选择`);
          return;
        }
        // 走关闭成功状态更新接口保存计划
        savePlan(resultTableData, "暂停");
        // ElMessage.success("批量关闭成功");
      })
      .catch(() => {
        // ElMessage({
        //   type: "info",
        //   message: "已取消",
        // });
      });
  }
}

// 批量取消暂停
const cancelPauseLoading = ref(false);
function cancelPausePlan() {
  if (!ids.value.length) {
    ElMessage.warning("请选择数据");
    return;
  } else {
    ElMessageBox.confirm(
      "只有已暂停的计划可以取消暂停，请确认是否取消暂停所选数据?",
      "提示",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(async () => {
        let listIds: any = ""; //第几行数据  不能关闭提示
        const resultTableData = deepCopy(toRaw(tableData.value));
        resultTableData.map((item: any, index: number) => {
          if (item.isPause * 1 !== 1 && ids.value.indexOf(item.id) !== -1) {
            if (index % 2 === 0) {
              const newLine = (index + 2) / 2;
              listIds += `第${newLine}行、`;
            }
          } else if (
            item.isPause * 1 === 1 &&
            ids.value.indexOf(item.id) !== -1
          ) {
            item.isPause = 0;
          }
        });
        if (listIds.length) {
          // 提示未暂停的数据  不能取消暂停
          listIds = listIds.slice(0, listIds.length - 1);
          ElMessage.error(`${listIds}不能取消暂停，请重新选择`);
          return;
        }
        // 走关闭成功状态更新接口保存计划
        savePlan(resultTableData, "取消暂停");
        // ElMessage.success("批量关闭成功");
      })
      .catch(() => {
        // ElMessage({
        //   type: "info",
        //   message: "已取消",
        // });
      });
  }
}

let beforeDeleteData = ref([]);
const kk = ref(true);
// 批量删除
const deleteLoading = ref(false);
function deletePlan() {
  const idsSave = deepCopy(toRaw(ids.value));
  if (!ids.value.length) {
    ElMessage.warning("请选择数据");
    return;
  } else {
    ElMessageBox.confirm("请确认是否删除所选数据?", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        const tableDatas: any = [];
        beforeDeleteData.value = deepCopy(toRaw(tableData.value));
        // const resultTableData = deepCopy(toRaw(tableData.value));
        tableData.value.map((item: any, index) => {
          if (ids.value.indexOf(item?.key) !== -1 && item.id === "") {
            tableData.value.splice(index);
            kk.value = false;
          } else if (ids.value.indexOf(item.id) !== -1) {
            item.deleted = 1;
            tableDatas.push(item);
            kk.value = true;
          } else {
            kk.value = true;
            tableDatas.push(item);
          }
        });
        tableData.value = tableDatas;
        getSelectedAllocationIds();
        // 走删除状态更新接口保存计划
        if (tableData.value.length && kk.value) {
          // 走删除状态更新接口保存计划
          savePlan(tableData.value, "删除", idsSave);
        } else {
          ElMessage.success("删除成功！");
          kk.value = true;
        }
        // ElMessage.success("批量下达成功");
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除",
        });
      });
  }
}

// 批量下达
const issueLoading = ref(false);
function issueOrders() {
  // console.log("ids", ids);
  if (!ids.value.length) {
    ElMessage.warning("请选择数据");
    return;
  } else {
    ElMessageBox.confirm("请确认是否下达所选数据?", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        let listIds: any = ""; //第几行数据  不能下达提示
        const resultTableData = deepCopy(toRaw(tableData.value));
        resultTableData.map((item: any, index: number) => {
          if (item.planState * 1 > 0 && ids.value.indexOf(item.id) !== -1) {
            if (index % 2 === 0) {
              const newLine = (index + 2) / 2;
              listIds += `第${newLine}行、`;
            }
          } else if (
            item.planState * 1 === 0 &&
            ids.value.indexOf(item.id) !== -1
          ) {
            item.planState = 2;
          } else if (
            item.planState * 1 === 0 &&
            ids.value.indexOf(item.key) !== -1 &&
            !item.id
          ) {
            item.planState = 2;
          }
        });
        if (listIds.length) {
          // 提示已下达过的计划，不能重复下达
          listIds = listIds.slice(0, listIds.length - 1);
          ElMessage.error(`${listIds}不能重新下达，请重新选择`);
          return;
        }
        // 走下达状态更新接口保存计划
        savePlan(resultTableData, "下达");
        // ElMessage.success("批量下达成功");
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消下达",
        });
      });
  }
}
// 变更提交
const changeSubLoading = ref(false);
const changeSubmission = () => {
  // console.log("ids", ids);
  if (!ids.value.length) {
    ElMessage.warning("请选择数据");
    return;
  } else {
    ElMessageBox.confirm("请确认是否问题变更所选数据?", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        const resultTableData = deepCopy(toRaw(tableData.value));
        let type = true;
        let List = [];
        resultTableData.forEach((item: any, index: number) => {
          if (type) {
            if (item.planState * 1 === 0 && ids.value.indexOf(item.id) !== -1) {
              ElMessage.error("新增数据不能变更提交！！");
              List.push(item);
              type = false;
              return;
            } else if (
              item.planState * 1 === 0 &&
              ids.value.indexOf(item.key) !== -1 &&
              !item.id
            ) {
              type = false;
              List.push(item);
              ElMessage.error("新增数据不能变更提交！");
              return;
            } else {
              if (
                item.planState * 1 != 2 &&
                item.planState * 1 != 3 &&
                ids.value.indexOf(item.id) !== -1
              ) {
                type = false;
                List.push(item);
                ElMessage.error("只有已下达、生产中数据可以变更提交！");
                return;
              }
            }
          }
        });
        if (List.length == 0) {
          savePlan(resultTableData, "变更提交");
        }
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消变更提交",
        });
      });
  }
};
// // 后加的代码--设备

const changeDeviceLoading = ref(false);
const equDialogVisible = ref(false);
const formDataRef = ref();
const formData: any = ref({
  id: "",
  workOrderId: "",
  plantId: "",
  plantCode: "",
  workCenterId: "",
  workCenterCode: "",
  workCenterName: "",
  processId: "",
  processName: "",
  processCode: "",
  equipmentId: "",
  equipmentCode: "",
  equipmentName: "",
  remark: "",
  createUserId: "",
  createUserName: "",
});

// 临时存储数据
const equipment: any = ref([]);
// 临时存储数据
const process: any = ref(null);
// 关闭设备弹窗
const clearRuleEqu = () => {
  formDataRef.value.clearValidate();
  equDialogVisible.value = false;
  formData.value.id = "";
  formData.value.workOrderId = "";
  formData.value.plantId = "";
  formData.value.plantCode = "";
  formData.value.workCenterId = "";
  formData.value.workCenterCode = "";
  formData.value.workCenterName = "";
  formData.value.processId = "";
  formData.value.processName = "";
  formData.value.processCode = "";
  formData.value.equipmentId = "";
  formData.value.equipmentCode = "";
  formData.value.equipmentName = "";
  formData.value.remark = "";
  formData.value.createUserId = "";
  formData.value.createUserName = "";
  equipmentList.value = [];
  equipment.value = [];
  processList.value = [];
  details.value = [];
  process.value = null;
  totalList.value = [];
};
// 校验

const checkProcess = (rule: any, value: any, callback: any) => {
  if (process.value == "") {
    callback("请选择工序");
  } else {
    callback();
  }
};
const checkEquipment = (rule: any, value: any, callback: any) => {
  if (equipment.value.length == 0) {
    callback("请选择设备");
  } else {
    callback();
  }
};
const rulesFormData = reactive({
  process: [
    {
      required: true,
      validator: checkProcess,
      trigger: "change",
    },
  ],
  equipment: [
    {
      required: true,

      validator: checkEquipment,
      trigger: "change",
    },
  ],
});

const changeDevice = () => {
  // console.log("ids", ids);
  if (ids.value.length == 0) {
    ElMessage.warning("请选择一条数据添加设备！");
    return;
  } else if (ids.value.length != 1) {
    ElMessage.warning("只能选择一条数据添加设备！");
    return;
  } else {
    let type = true;
    let List = [];
    const result = resolveSaveData(tableData.value);
    result.forEach((item: any) => {
      if (!item.routingAllocationId) {
        List.push(item);
        ElMessage.error("请选择版本号才能选择设备！");
        return;
      }
    });
    // resultTableData.forEach((item: any, index: number) => {
    //   if (type) {
    //     if (!item.versionNo) {
    //       List.push(item);
    //       ElMessage.error("请选择版本号才能选择设备！");
    //       type = false;
    //       return;
    //     } else {
    //     }
    //   }
    // });
    if (List.length == 0) {
      getProcessList();

      //编辑时赋值
    }
  }
};

// 编辑时赋值
const editEqu = async () => {
  console.log(ids.value[0]);

  const { data } = await request({
    url: "/mes/mesworkorderequip/getList",
    method: "post",
    data: { workOrderId: ids.value[0] },
  });
  if (data.length > 0) {
    process.value = data[0].processId;
    processList.value.forEach((item) => {
      if (item.id == process.value) {
        equipmentList.value = item.details;
      }
    });
    equipment.value = [];
    data.forEach((item) => {
      equipment.value.push(item.equipmentId);
    });
  }
};

//  获取工序列表
const processList = ref([]);
// 要穿总的设备列表
const totalList = ref([]);
// 临时存储
const temporary = ref("");
const getProcessList = async () => {
  // 选中的整行数据
  const processData = ref([]);
  // 根据选中的id 获取这一行的数据
  if (ids.value.length == 1) {
    const result = resolveSaveData(tableData.value);
    result.forEach((item: any) => {
      if (item.id == ids.value[0] || item.key == ids.value[0]) {
        processData.value = item;
      }
    });
  }
  // 用这一行的数据作为参数 获取工序列表
  const { data } = await request({
    url: "/mes/mesworkorder/queryRoutingProcess",
    method: "post",
    data: processData.value,
  });
  processList.value = data;

  // 默认 刚打开 选择第一个工序及 设备的所有数据
  if (processList.value.length > 0) {
    // 判断是否是新增时点的设备还是编辑时点的设备 赋值totalList.value
    if (!processData.value.workOrderEquipList) {
      console.log("wu");
      processList.value.forEach((item) => {
        item.processEquipment.forEach((item1) => {
          totalList.value.push(item1);
        });
      });
      console.log(totalList.value);
    } else {
      console.log("you");
      processData.value.workOrderEquipList.forEach((item) => {
        totalList.value.push(item);
      });
      console.log("you", totalList.value);
    }
    process.value = data[0].processId;
    // 记录前工序id
    temporary.value = data[0].processId;
    // 根据工序id获取设备列表
    processList.value.forEach((item) => {
      if (item.processId == process.value) {
        equipmentList.value = item.processEquipment;
      }
    });
    // 根据设备列表选中所有数据
    equipment.value = [];
    equipmentList.value.forEach((item) => {
      // 页面展示的选中数据
      totalList.value.forEach((item1) => {
        if (item.equipmentId == item1.equipmentId) {
          equipment.value.push(item.equipmentId);
        }
      });
    });
    // 打开弹窗
    equDialogVisible.value = true;
    // 编辑
    // editEqu();
    // equipmentList.value = data.details;
    // console.log(processList.value);
  } else {
    ElMessage.error("该订单没有工序，请先添加工序！");
    return;
  }
};

// 当工序改变时
const changProcess = (e) => {
  // 当工序改变时 去掉改变之前的工序的旧设备 添加之前工序的改变新设备
  totalList.value = totalList.value.filter((item) => {
    return item.processId != temporary.value;
  });
  // 判断是否有选中的数据
  if (equipment.value.length > 0) {
    equipmentList.value.forEach((item) => {
      equipment.value.forEach((item1) => {
        if (item.equipmentId == item1) {
          totalList.value.push(item);
        }
      });
    });
  }

  // 改变之后进行操作
  equipmentList.value = [];
  equipment.value = [];
  processList.value.forEach((item) => {
    if (item.processId == e) {
      equipmentList.value = [];
      item.processEquipment.forEach((item1) => {
        equipmentList.value.push(item1);
      });
    }
  });
  equipmentList.value.forEach((item) => {
    totalList.value.forEach((item1) => {
      if (item.equipmentId == item1.equipmentId) {
        equipment.value.push(item.equipmentId);
      }
    });
  });
};

// 根据工序id获取设备列表
const equipmentList = ref([]);
const getEquipmentList = async (id) => {
  const { data } = await request({
    url: "/mes/mesworkorderequip/getList",
    method: "post",
    data: { processId: id },
  });
  equipmentList.value = data;
};

// 当设备改变时
const changEquipment = () => {
  console.log(formData.value.equipmentList);
};

// 保存 设备
const details: any = ref([]);
const saveEqu = () => {
  // 当工序改变时 去掉改变之前的工序的旧设备 添加之前工序的改变新设备
  totalList.value = totalList.value.filter((item) => {
    return item.processId != process.value;
  });
  // 判断是否有选中的数据
  console.log("设备", equipmentList.value);

  if (equipment.value.length > 0) {
    equipmentList.value.forEach((item) => {
      equipment.value.forEach((item1) => {
        if (item.equipmentId == item1) {
          totalList.value.push(item);
        }
      });
    });
  }
  console.log("baocun", totalList.value);

  if (totalList.value.length > 0) {
    totalList.value.forEach((item) => {
      details.value.push({
        id: "",
        workOrderId: "",
        plantId: "",
        plantCode: "",
        workCenterId: "",
        workCenterCode: "",
        workCenterName: "",
        processId: item.processId,
        processName: item.processName,
        processCode: item.processCode,
        equipmentId: item.equipmentId,
        equipmentCode: item.equipmentCode,
        equipmentName: item.equipmentCode,
        remark: "",
        createUserId: "",
        createUserName: "",
      });
    });
    // processList.value.forEach((item) => {
    //   if (item.id == process.value) {
    //     details.value.forEach((item1) => {
    //       item1.processName = item.processName;
    //       item1.processCode = item.processCode;
    //     });
    //   }
    // });
  } else {
    details.value = [];
  }

  const resultTableData = deepCopy(toRaw(tableData.value));
  savePlan(resultTableData, "添加设备");
};

// 计划确认
const planSubmitbLoading = ref(false);
const planSubmit = () => {
  if (!ids.value.length) {
    ElMessage.warning("请选择数据");
    return;
  } else {
    ElMessageBox.confirm("请确认是否确认所选数据?", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        const resultTableData = deepCopy(toRaw(tableData.value));
        let type = true;
        let List = [];
        resultTableData.forEach((item: any, index: number) => {
          console.log("item.isCasual", item.isCasual);

          if (type) {
            if (item.isCasual == 0 && ids.value.indexOf(item.id) !== -1) {
              ElMessage.error("只有临时数据可以计划确认！");
              List.push(item);
              type = false;
              return;
            }
          }
        });
        if (List.length == 0) {
          savePlan(resultTableData, "计划确认");
        }
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消计划确认",
        });
      });
  }
};

//
const currentYield = ref(); // 当前班产
const searchParam = ref<SearchType>({ ...searchParamInit });
const loading = ref(false);
const oneLineTable = ref();
const elderData: any = ref();

const tableLoadRate: any = ref([]);
// 搜索
const search = async () => {
  loading.value = true;
  tableData.value = [];
  const { data } = await request({
    url: "/mes/mesWorkOrderOther/queryByWeek",
    method: "post",
    data: toRaw(searchParam.value),
  }).catch(() => {
    loading.value = false;
  });

  // 获取接口原数据
  elderData.value = deepCopy(data ?? []);

  searchedCompanyId.value = toRaw(companyId.value);

  searchedParams.value = toRaw(searchParam.value);
  isSearched.value = true;
  // 获取班产量
  // currentYield.value = await getCurrentYield(searchParam.value.workCenterId);

  // 最新表格时间处理
  currentWeekDetail.value = getCurrentWeekDetail(
    searchParam.value,
    freeDetail.value
  );
  // 最新休息日数据
  const arr: any = [];
  currentWeekDetail.value.map((e: any) => {
    if (e.isFree === true) {
      arr.push(
        searchedParams.value.planYear + "-" + e.date.split("/").join("-")
      );
    }
  });
  freeDayDetail.value = arr;

  // 一行表格初始化
  // oneLineTable.value = getOneLineDate(
  //   currentWeekDetail.value,
  //   toRaw(searchParam.value.planYear)
  // );
  // 表格数据处理 mockData
  // tableData.value = resolveSearchData(
  //   data,
  //   currentWeekDetail.value,
  //   toRaw(searchParam.value.planYear)
  // );
  tableLoadRate.value = await calculateLoadRate(data);

  tableData.value = resolveSearchData(
    data,
    currentWeekDetail.value,
    toRaw(searchParam.value.planYear)
  );

  // 计算当前未排数量
  data?.forEach((item, index) => {
    const selfIndex = (index + 1) * 2 - 2;
    computedUnPlanQuantity(selfIndex);
    computedPlanWeekQuantityRate(selfIndex);
  });

  loading.value = false;

  // 获取当前页面已选的物料号ids
  getSelectedAllocationIds();
};

const reset = () => {
  searchParam.value = { ...searchParamInit };
  if (userPlantInfo.value?.id) {
    selectPlant(userPlantInfo.value?.id);
  } else {
    workShopList.value = [];
  }
  tableData.value = [];
  workCenterDetail.value = {};
  isSearched.value = false;
};

// 获取周列表
const monthOptions = ref<OptionType[]>();

// 获取年度列表
const yearOptions = ref();

// 年度变更重新获取月份
function selectYear(e: number) {
  isSearched.value = false;
  if (e) {
    searchParam.value = { ...searchParam.value, planWeek: "" };
    monthOptions.value = getMonthList(e);
  } else {
    monthOptions.value = [];
    searchParam.value = { ...searchParam.value, planWeek: "" };
  }
}

// 工厂编号列表
const plantList: any = ref([]);
// 工作中心列表
const workShopList: any = ref([]);

// 当前选中的工厂
const companyId = ref("");
const searchedCompanyId = ref("");
async function selectPlant(e: string) {
  isSearched.value = false;
  workShopList.value = (await getOtherWorkShopList(e, 5)) ?? [];
  searchParam.value = { ...searchParam.value, workCenterId: "" };
  companyId.value =
    plantList.value.find((item) => item.id === e)?.parentId ?? "";
}

onMounted(async () => {
  userPlantInfo.value?.id && selectPlant(userPlantInfo.value?.id);
  // 获取工厂列表
  plantList.value = await getPlantList();
  searchParam.value.plantId = plantList.value[0].id;
  selectPlant(searchParam.value.plantId);
  // 获取年列表
  yearOptions.value = await getYearList();
  // 获取周搜索列表
  monthOptions.value = getMonthList(currentYear);
  // 表格日期对象 [{date: '05/06', week: 1}, {date: '05/07', week: 2}...]
  currentWeekDetail.value = getCurrentWeekDetail(searchParam.value);
});

// 导入周数据
const weekImportRef = ref();
const uploadErrorRef = ref();
const errorDataList = ref([]);
async function weekImportApiFunc(formdata: FormData, config: any) {
  await request
    .post("/mes/mesworkorder/upload", formdata, config)
    .then((res: any) => {
      weekImportRef.value.resCode = res.code;
      weekImportRef.value.sucessTatol = res.data.completeNo;
      if (res.data.errorList.length > 0) {
        errorDataList.value = res.data.errorList;
        uploadErrorRef.value.errorBox = true;
      }
    })
    .catch((e) => {
      weekImportRef.value.resCode = 500;
    });
}
const weekBatchImport = () => {
  if (
    !searchParam.value.planWeek ||
    !searchParam.value.plantId ||
    !searchParam.value.planYear
  ) {
    ElMessage.error("请选择工厂、工作周、工作年份，再操作");
  } else {
    let newSearchParam = { ...searchParam.value };
    newSearchParam.groupType = 5;
    let params = {
      title: "导入周计划",
      tempApi: "/mes/mesworkorder/exportTemp", //模板下载
      importApi: weekImportApiFunc, // 导入
      getTableList: startSearch1, // 成功后回调
      isShowTemp: true,
      fileTypes: ".xls",
      searchParam: newSearchParam,
    };
    weekImportRef.value.acceptParams(params);
  }
};

// 后加的代码--
async function startSearch1() {
  if (isSearched.value == true) {
    if (!searchParam.value.plantId) {
      ElMessage.error("请选择工厂");
      return;
    } else if (!searchParam.value.workCenterId) {
      ElMessage.error("请选择工作中心");
      return;
    } else if (!searchParam.value.planYear) {
      ElMessage.error("请选择年份");
      return;
    } else if (!searchParam.value.planWeek) {
      ElMessage.error("请选择工作周");
      return;
    } else {
      // 工作中心详情
      const { workCenterId, planYear, plantId } = searchParam.value;
      workCenterDetail.value = await getWorkCenterDetail(workCenterId);
      dateshiftCount.value = await getDateshiftCount(searchParam.value);
      if (dateshiftCount.value.length === 0) {
        ElMessage.error("请先设置排班");
        return;
      }
      // 获取最大负荷率
      maxCapacityLoad.value = workCenterDetail.value.maxCapacityLoad;
      // 获取休息日数据
      freeDetail.value = await getFreeDetails(plantId, planYear);
      // 获取物料下拉列表
      routingAllocationIdList.value = await getMaterialList(
        searchParam.value.plantId,
        searchParam.value.workCenterId
      );
      search();
    }
  }
}
const downLoadExcel = () => {
  if (!isSearched.value) {
    ElMessage.error("请切换到对应排产后，再操作");
  } else {
    useDownload(
      "/mes/mesworkorder/export",
      `计划排程-周排产(装配)`,
      searchedParams.value,
      true,
      ".xls"
    );
  }
};

// 导入日数据
const dailyImportRef = ref();
async function dailyImportApiFunc(formdata: FormData, config: any) {
  await request.post("/mdm/mdmmatgroup/upload", formdata, config);
}
const dailyBatchImport = () => {
  if (!isSearched.value) {
    ElMessage.error("请切换到对应排产后，再操作");
  } else {
    let params = {
      title: "导入日计划",
      tempApi: "/mdm/mdmmatgroup/exportTemp", //模板下载
      importApi: dailyImportApiFunc, // 导入
      getTableList: search, // 成功后回调
    };
    dailyImportRef.value.acceptParams(params);
  }
};

// 工作中心详情
const workCenterDetail = ref();
// 最大负荷率
const maxCapacityLoad = ref();
// 休息日设定信息
const freeDetail = ref();
// 物料列表
const routingAllocationIdList = ref();
// 日班次
const dateshiftCount = ref();

async function startSearch() {
  tableData.value = [];
  isSearched.value = false;
  if (!searchParam.value.plantId) {
    ElMessage.error("请选择工厂");
    return;
  } else if (!searchParam.value.workCenterId) {
    ElMessage.error("请选择工作中心");
    return;
  } else if (!searchParam.value.planYear) {
    ElMessage.error("请选择年份");
    return;
  } else if (!searchParam.value.planWeek) {
    ElMessage.error("请选择工作周");
    return;
  } else {
    // 工作中心详情
    const { workCenterId, planYear, plantId } = searchParam.value;
    workCenterDetail.value = await getWorkCenterDetail(workCenterId);
    dateshiftCount.value = await getDateshiftCount(searchParam.value);
    if (dateshiftCount.value.length === 0) {
      ElMessage.error("请先设置排班");
      return;
    }
    // 获取最大负荷率
    maxCapacityLoad.value = workCenterDetail.value.maxCapacityLoad;
    // 获取休息日数据
    freeDetail.value = await getFreeDetails(plantId, planYear);
    // 获取物料下拉列表
    routingAllocationIdList.value = await getMaterialList(
      searchParam.value.plantId,
      searchParam.value.workCenterId
    );
    search();
  }
}

// 当前页面已选的物料号ids
const selectedRoutingAllocationIds: any = ref([]);
const selectedRoutingAllocationPlan: any = ref([]);
// 选择物料号
async function changeRoutingAllocation(data: string, index: number) {
  const indexArr = [index, index + 1];
  if (data) {
    const current = routingAllocationIdList.value.filter((e) => e.id === data);
    const res: any = await getCurrentYield(
      tableData.value[index].routingAllocationId,
      searchParam.value.workCenterId
    );
    indexArr.map((item) => {
      tableData.value[item].routingAllocationId = current[0]?.id || "";
      tableData.value[item].routingId = current[0]?.routingId || "";
      tableData.value[item].actualYield = res.actualYield;
      tableData.value[item].yield = res.maxYield;
      tableData.value[item].materialId = current[0]?.materialId;
      tableData.value[item].materialCode = current[0]?.materialCode;
    });
  } else {
    indexArr.map((item) => {
      tableData.value[item].routingAllocationId = "";
      tableData.value[item].routingId = "";
      tableData.value[item].yield = "";
      tableData.value[item].materialId = "";
      tableData.value[item].materialCode = "";
    });
  }
  getSelectedAllocationIds();
}

// 获取当前页面已选的物料号ids
function getSelectedAllocationIds() {
  const selectArr: any[] = [];
  const selectArr1: any[] = [];
  tableData.value.map((item, index) => {
    if (item.planState * 1 !== 5) {
      selectArr.push(item.routingAllocationId);
      selectArr1.push(item.planBatch);
    }
  });
  selectedRoutingAllocationIds.value = Array.from(new Set(selectArr));
  selectedRoutingAllocationPlan.value = Array.from(new Set(selectArr1));
}

function changePlanQuantity(e, index) {
  // 计算未排数量  待计算  用计划减去每隔的和
  computedUnPlanQuantity(index);
  if (
    tableData.value[index].planState * 1 != 2 &&
    tableData.value[index + 1].planState * 1 != 2 &&
    tableData.value[index].planState * 1 != 3 &&
    tableData.value[index + 1].planState * 1 != 3
  ) {
    computedPlanWeekQuantity(index);
  }
  computedPlanWeekQuantityRate(index);
}

// 计算周计划数量
function computedPlanWeekQuantity(index) {
  // console.log("开始计算", index);
  const indexArr = [index, index + 1];
  // let totalQuantity = 0;
  // tableData.value[index].newOrders.map((orderItem) => {
  //   orderItem.newClasses.map((count) => {
  //     totalQuantity += count.planQuantity * 1;
  //   });
  // });
  // 修改第一行和第二行的值
  indexArr.map((tableIndex) => {
    tableData.value[tableIndex].planWeekQuantity =
      tableData.value[tableIndex].planQuantity;
  });
}

// 计算周计划率
function computedPlanWeekQuantityRate(index) {
  // console.log("开始计算", index);
  const indexArr = [index, index + 1];
  // let totalQuantity = 0;
  // tableData.value[index].newOrders.map((orderItem) => {
  //   orderItem.newClasses.map((count) => {
  //     totalQuantity += count.planQuantity * 1;
  //   });
  // });
  // 修改第一行和第二行的值
  indexArr.map((tableIndex) => {
    // ${(maxCapacityLoad.value / 100).toFixed(
    //   2)
    tableData.value[tableIndex].planWeekQuantityRate =
      (
        Number(tableData.value[tableIndex].planFinishQuantity) /
        Number(tableData.value[tableIndex].planQuantity)
      ).toFixed(2) == "NaN"
        ? 0
        : (
            Number(tableData.value[tableIndex].planFinishQuantity) /
            Number(tableData.value[tableIndex].planQuantity)
          ).toFixed(2);
  });
}

// 接口自动分配
async function rulePlanQuantity(e, index) {
  formRef.value
    .validateField(index + ".planQuantity")
    .then(async (res) => {
      const resultTableData = deepCopy(toRaw(tableData.value));
      resultTableData[index].autoAllocation = 1;
      resultTableData[index + 1].autoAllocation = 1;
      const result = resolveSaveData(resultTableData);
      tableData.value[index].autoAllocationLoading = true;
      const { data, code } = await request({
        url: "/mes/mesworkorder/autoAllocation",
        method: "post",
        data: result,
      }).finally(() => {
        tableData.value[index].autoAllocationLoading = true;
      });
      if (code === 200) {
        ElMessage.success(`自动分配成功`);
        tableLoadRate.value = await calculateLoadRate(data);
        tableData.value = resolveSearchData(
          data,
          currentWeekDetail.value,
          toRaw(searchParam.value.planYear)
        );

        // 计算当前未排数量
        data?.forEach((item, index) => {
          const selfIndex = (index + 1) * 2 - 2;
          computedUnPlanQuantity(selfIndex);
          computedPlanWeekQuantityRate(selfIndex);
        });

        // 获取当前页面已选的物料号ids
        getSelectedAllocationIds();
      }
    })
    .catch(() => {});
}

// 校验当前班次是否存在 planDate计划日期、cellIndex当前班次
function isWorkingCrew(planDates: string, cellIndex: number) {
  let result = false;
  const current = dateshiftCount.value.filter((e: any) =>
    e.planDate.split("/").join("-").includes(planDates)
  );
  if (current && current[0] && current[0].shiftCount > cellIndex) {
    result = true;
  }
  return result;
}

// 计算未排产数量
function computedUnPlanQuantity(index) {
  // console.log("开始计算", index);
  const indexArr = [index, index + 1];
  let totalQuantity = 0;
  tableData.value[index].newOrders.map((orderItem) => {
    orderItem.newClasses.map((count) => {
      totalQuantity += count.planQuantity * 1;
    });
  });
  // 修改第一行和第二行的值
  indexArr.map((tableIndex) => {
    const computedNumber = Math.floor(
      tableData.value[tableIndex].planQuantity - totalQuantity
    );
    const number = computedNumber < 0 ? 0 : computedNumber;
    tableData.value[tableIndex].unPlanQuantity = number;
  });
}

const isOverLoadRate = ref(false);

watch(
  () => tableLoadRate.value,
  (newValue) => {
    const overArrs = newValue?.filter(
      (item) => Number(item) > maxCapacityLoad.value / 100
    );
    isOverLoadRate.value = overArrs && overArrs?.length ? true : false;
  },
  {
    deep: true,
  }
);
const saveLoading = ref(false);
// function bornDescriptionCode(id, list) {}
function savePlan(resultTableData: any, message: "", idsSave?: any) {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      const postUrl = resolveUrl(message);
      const idList = message == "删除" ? idsSave : ids.value;

      // 添加selected被选中标识
      resultTableData.forEach((item: any, index: number) => {
        item.selected = 0;
        if (idList.indexOf(item.id) !== -1 || idList.indexOf(item.key) !== -1) {
          item.selected = 1;
        } else {
          item.selected = 0;
        }
      });

      // 已下达数据校验,获取下达时被勾选的数据,判断钢卷和计划数量是否为空
      if (message === "下达") {
        for (let i = 0; i < resultTableData.length; i++) {
          if (
            i % 2 === 0 &&
            resultTableData[i].selected == 1 &&
            resultTableData[i].planState != 5
          ) {
            let noPlanQuantity = true;
            for (let j = 0; j < resultTableData[i].newOrders.length; j++) {
              const newClasses = resultTableData[i].newOrders[j].newClasses;
              for (let b = 0; b < newClasses.length; b++) {
                if (
                  newClasses[b].planQuantity &&
                  newClasses[b].planQuantity != 0
                ) {
                  noPlanQuantity = false;
                  break;
                }
              }
            }

            if (noPlanQuantity) {
              ElMessage.error("下达的数据，本周的计划分配数量不能全为空");
              return;
            }
          }
        }
      }
      // 判断本周的计划分配数量不能超过总计划数量
      if (message != "删除" && message != "关闭") {
        let isSum = false;
        console.log("resultTableData", resultTableData);

        resultTableData.forEach((item, i) => {
          if (item.planState == 0) {
            if (item.orderPlanList) {
              console.log("zou");

              let sum = 0;
              item.orderPlanList.forEach((item2) => {
                sum += item2.planQuantity * 1;
              });
              if (sum > item.planQuantity * 1) {
                console.log(sum, item.planQuantity * 1);
                isSum = true;
                return;
              }
            }
          }
        });
        if (isSum) {
          ElMessage.error("本周的计划分配数量不能超过总计划数量");
          return;
        }
      }
      // 排查当前是否有超负荷率的情况
      if (isOverLoadRate.value) {
        // 保存时判断已排数量不能超过总数量

        ElMessageBox.confirm(
          "当前生产计划有负荷率超标情况，请确定是否继续操作",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            lastSubmit(resultTableData, message, postUrl);
          })
          .catch(() => {
            ElMessage({
              type: "info",
              message: "已取消",
            });
          });
      } else {
        lastSubmit(resultTableData, message, postUrl);
      }
    } else {
      // tableData.value = beforeDeleteData.value;
      if (message == "添加设备") {
        equDialogVisible.value = false;
      }
      ElMessage.warning("请完善基础信息");
    }
  });
}

// 最终操作接口
async function lastSubmit(
  resultTableData: any,
  message: string,
  postUrl: string
) {
  // 后加打代码--用于添加设备集合
  const result = resolveSaveData(resultTableData);
  if (message == "添加设备" && ids.value.length == 1) {
    let detas = details.value;
    result.forEach((item) => {
      if (item.id == ids.value[0] || item.key == ids.value[0])
        item.workOrderEquipList = detas;
      clearRuleEqu();
    });
  }
  result.forEach((item) => {
    if (item.groupType == null && !item.groupType) {
      item.groupType = 5;
    }
  });
  showLoading(message, true);
  const { data, code } = await request({
    url: postUrl,
    method: "post",
    data: result,
  })
    .finally(() => {
      showLoading(message, false);
    })
    .catch((e) => {
      if (message === "删除") {
        tableData.value = beforeDeleteData.value;
      }
    });
  if (code === 200) {
    ElMessage.success(`${message}成功`);
    search(); // 更新数据
  }
}

function resolveUrl(message) {
  let url = "";
  if (message == "保存") {
    url = "/mes/mesWorkOrderOther/saveWeekFirst";
  } else if (message == "下达") {
    url = "/mes/mesWorkOrderOther/issuePlan";
  } else if (message == "删除") {
    url = "/mes/mesWorkOrderOther/deletePlan";
  } else if (message == "关闭") {
    url = "/mes/mesWorkOrderOther/closePlan";
  } else if (message == "暂停") {
    url = "/mes/mesWorkOrderOther/pausePlan";
  } else if (message == "计划确认") {
    url = "/mes/mesWorkOrderOther/validate";
  } else if (message == "取消暂停") {
    url = "/mes/mesWorkOrderOther/resumePlan";
  } else if (message == "变更提交") {
    // 更改内容 变更提交
    url = "/mes/mesWorkOrderOther/submitPlan";
  } else if (message == "添加设备") {
    // 设备
    url = "/mes/mesWorkOrderOther/saveWeekFirst";
  } else {
    url = "/mes/mesWorkOrderOther/saveWeekFirst";
  }
  return url;
}

function showLoading(message, loading) {
  if (message == "保存") {
    saveLoading.value = loading;
  } else if (message == "下达") {
    issueLoading.value = loading;
  } else if (message == "删除") {
    deleteLoading.value = loading;
  } else if (message == "关闭") {
    closeLoading.value = loading;
  } else if (message == "变更提交") {
    changeSubLoading.value = loading;
  } else if (message == "暂停") {
    pauseLoading.value = loading;
  } else if (message == "取消暂停") {
    cancelPauseLoading.value = loading;
  } else if (message == "添加设备") {
    changeDeviceLoading.value = loading;
  } else if (message == "计划确认") {
    planSubmitbLoading.value = loading;
  }
}

const open = async (
  rowData: any,
  rowIndex: number,
  monthIndex: number,
  cellIndex: number,
  quantity: number | string
) => {
  if (
    rowData.planState * 1 !== 0 &&
    rowData.planState * 1 !== 2 &&
    rowData.planState * 1 !== 3
  ) {
    return;
  }
  if (
    !isWorkingCrew(
      tableData.value[rowIndex].newOrders[monthIndex].planDate,
      cellIndex
    )
  ) {
    ElMessage.error("当前未设置班次");
    return;
  }
  if (!tableData.value[rowIndex].routingAllocationId) {
    ElMessage.error("请先选择工艺路线");
    return;
  }
  if (tableData.value[rowIndex].planQuantity * 1 === 0) {
    ElMessage.error("请先输入计划数量");
    return;
  }

  if (
    tableData.value[rowIndex].planState * 1 === 0 ||
    tableData.value[rowIndex].planState * 1 === 2 ||
    tableData.value[rowIndex].planState * 1 === 3
  ) {
    tableData.value[rowIndex].autoAllocation = 1;
    tableData.value[rowIndex].newOrders[monthIndex].newClasses[
      cellIndex
    ].autoAllocationOne = 1;

    const result = resolveSaveData(tableData.value);

    if (
      tableData.value[rowIndex].newOrders[monthIndex].newClasses[cellIndex]
        .planQuantity == ""
    ) {
      tableData.value[rowIndex].newOrders[monthIndex].newClasses[
        cellIndex
      ].autoAllocationOne = 1;
      // tableData.value[rowIndex].newOrders[monthIndex].newClasses[
      //   cellIndex
      // ].planQuantity = 0;
      let one = {};
      one =
        tableData.value[rowIndex].newOrders[monthIndex].newClasses[cellIndex];
      one.autoAllocationOne = 1;
      result[rowIndex / 2].orderPlanList.push(one);
    }

    // 获取未排班产数量
    ruleForm.noYelid = await getNoYelid(result);

    tableData.value[rowIndex].autoAllocation = 0;
    tableData.value[rowIndex].newOrders[monthIndex].newClasses[
      cellIndex
    ].autoAllocationOne = 0;

    // ruleForm.quantity = quantity ? quantity : tableData.value[rowIndex].yield;
    ruleForm.rowData = rowData;
    ruleForm.rowIndex = rowIndex;
    ruleForm.monthIndex = monthIndex;
    ruleForm.cellIndex = cellIndex;
    ruleForm.unPlanQuantity = tableData.value[rowIndex].unPlanQuantity;
    ruleForm.yelid = tableData.value[rowIndex].yield;
    // ruleForm.noYelid = tableData.value[rowIndex].yield;
    // 判断班产
    if (quantity * 1 != 0) {
      ruleForm.quantity = quantity;
    } else {
      if (ruleForm.unPlanQuantity * 1 == 0) {
        ruleForm.quantity = 0;
      } else if (ruleForm.unPlanQuantity * 1 < ruleForm.noYelid * 1) {
        ruleForm.quantity = ruleForm.unPlanQuantity * 1;
      } else if (ruleForm.unPlanQuantity * 1 == ruleForm.noYelid * 1) {
        ruleForm.quantity = ruleForm.noYelid * 1;
      } else if (ruleForm.unPlanQuantity * 1 > ruleForm.noYelid * 1) {
        ruleForm.quantity = ruleForm.noYelid * 1;
      } else if (ruleForm.noYelid * 1 == 0) {
        ruleForm.quantity = 0;
      }
    }
    dialogVisible.value = true;
    inputAutoFocus();
  }
};
function getNoYelid(result) {
  return new Promise(async (resolve, reject) => {
    const { data } = await request({
      url: "/mes/mesworkorder/autoAllocationone",
      method: "post",
      data: result,
    });
    resolve(data);
  });
}
</script>
<style lang="scss" scoped>
@import url("@/views/mes/weeklyProducePlan/index.scss");

:deep(.planDialog .el-dialog__body) {
  padding: 20px 20px 0px;
}

:deep(.el-table--border th.bg-free) {
  background-color: #fef0f0 !important;
  color: rgba(248, 113, 113, 1) !important;
}

:deep(.percent_cell .cell) {
  width: 100%;
  height: 29px;
  line-height: 29px;
  display: block;
  padding: 0 !important;

  div {
    display: block;
    height: 100%;
    width: 100%;

    span {
      display: block;
      height: 100%;
      width: auto;
      padding: 0 7px;
    }
  }
}
</style>
